/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src.view.saving;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
import org.primefaces.event.CloseEvent;
import src.domain.saving.Saving;
import src.domain.saving.Savtrxgl;
import src.domain.saving.Savwd;
import src.domain.security.Users;
import src.services.saving.SavingModel;
import src.services.saving.SavtrxglModel;
import src.services.saving.SavwdModel;
import src.util.Constanta;
import src.util.Messager;
import src.view.security.LoginBean;

/**
 *
 * @author jay
 */
@ManagedBean
@SessionScoped
public class SavwdglBean implements Serializable {

    private Savwd savwd;  
    private List<Savtrxgl> availableGL;  
    
    private SavwdModel savhelper;
    private boolean editMode = false, authorized=false, insertionMode=false;
    private Integer branchId, bankId;
    private BigDecimal saldoAwal = BigDecimal.ZERO, saldoAkhir = BigDecimal.ZERO;
    private Users user;
    private String defaultButton="doNothingSavwdgl";
    private boolean showLookup=false;
    
    public SavwdglBean() {
        super();
        ambilUser();
        this.savhelper = new SavwdModel();
        newData();
        editMode = false;
        authorized = false;
    }
                
    private boolean cekConfig() {
        boolean complete=true;
        this.branchId = user.getBranch().getBranchId();
        this.bankId = user.getSavBankId(); 
        
        if (this.branchId==null || this.bankId==null) complete=false;
                    
        if(complete==false) Messager.showWarning("savingUnconfig");
        
        return complete;
    }

    public boolean isShowLookup() {
        return showLookup;
    }

    public void setShowLookup(boolean showLookup) {
        this.showLookup = showLookup;
    }
    
    public boolean isEditMode() {
        return editMode;
    }

    public boolean isAuthorized() {
        return authorized;
    }
    
    public Savwd getSavwd() {
        return savwd;
    }

    public void setSavwd(Savwd savwd) {
        this.savwd = savwd;
    }

    public List<Savtrxgl> getAvailableGL() {
        return availableGL;
    }
        
    public BigDecimal getSaldoAkhir() {
        return saldoAkhir;
    }

    public BigDecimal getSaldoAwal() {
        return saldoAwal;
    }

    public void getSavingSrc(String accntNo) {
        boolean found = false;
        if ("null".equals(accntNo)) accntNo = savwd.getSaving().getAccountNo();

        if (accntNo!=null ) {
        
            this.saldoAwal = BigDecimal.ZERO;
            this.saldoAkhir = BigDecimal.ZERO;
            SavingModel helper = new SavingModel();
            Saving saving = helper.getByAccount(accntNo);
                        
            if (saving==null) {
                Messager.showWarning("accntNotFound");
                this.savwd.setSaving(new Saving());
                
            } else {
                this.savwd.setSaving(saving);
                this.saldoAwal = savwd.getSaving().getBalance();
                found=true;
                defaultButton="doNothingSavwdgl";
                
                if (savwd.getAmount() != null)
                    this.saldoAkhir = this.saldoAwal.subtract(savwd.getAmount());
            }
        }
        RequestContext.getCurrentInstance().addCallbackParam("success", found); 
    }
    
    public void calcSaldoAhir() {
        if (savwd.getAmount() != null)
            this.saldoAkhir = saldoAwal.subtract(savwd.getAmount());
    }
    
    private void initForm() {
        this.editMode = true;
        this.authorized = true;
        defaultButton="doNothingSavwdgl";      
        showLookup=false;
        Map filter = new HashMap<>();
        filter.put("transactionName", Constanta.SAV_GL_DROPDOWN);
        this.availableGL = new SavtrxglModel().findAll(filter);
        saldoAkhir= BigDecimal.ZERO;
        saldoAwal= BigDecimal.ZERO;
    }
        
    public final void newData() {  
        initForm();
        cekConfig();
        if (this.savwd!=null) savwd = null;
        this.savwd = new Savwd();
        this.savwd.setBranchId(branchId);
        this.savwd.setBankId(bankId);
        //this.savwd.setLinkGlaccountId(glaccntId);
        insertionMode = true;
    }
        
    public boolean validate() {
        boolean hasil=true;
        
        BigDecimal balance = savwd.getSaving().getBalance();
        BigDecimal ddAmount = savwd.getAmount();
        
        //-1 less then
        //+0 equals
        //+1 greather
        
        if(balance.compareTo(ddAmount)==-1) {
            Messager.showWarning("balanceKurang");
            hasil=false;
        }
        else if(ddAmount.compareTo(BigDecimal.valueOf(0)) < 1) {
            Messager.showWarning("balanceRequired");
            hasil=false;
        }
        
        if (hasil==true) hasil = cekConfig();
        
        return hasil;
    }
    
    private void validateLimit() {
        this.authorized = true;
                
        savwd.setUserId(user.getUserId());
        Integer authorizedId = this.savhelper.authorized(savwd.getSavwdId());
        
        savwd.setApprovalUid(authorizedId);
        
        //belum diotorisasi, cek validasi
        if (authorizedId == null) {
            BigDecimal ddAmount = savwd.getAmount();
            BigDecimal ddAmountAlowed = user.getUgroup().getSavMaxWd();
        
            if(ddAmount.compareTo(ddAmountAlowed) >= 0) this.authorized=false;
            
            //jika dlm rage limit, authorizedId = userId
            else savwd.setApprovalUid(user.getUserId());
        }
        
        //men-triger history and balance
        savwd.setPosted(authorized);
    }
    
    public void save() {
        validateLimit();
        
        boolean success = savhelper.saveData(savwd);
        //this.editMode = (!success || !authorized);
        this.editMode = (!success);
        
        Messager.showSaveUpdateStatus(success);     
        
        if (!authorized && success)
            Messager.showWarning("unauthorized");    
        
        //ngahaja. biar inputBox bisa ngisi klo eror
        if (!success) authorized = true;
        else {
            
            //kalo sukses & athorized....
            if (authorized) authorized = false;
        } 
        
        // re-insert
        if (!success && insertionMode) savwd.setSavwdId(null);
        else insertionMode = false;
        
        RequestContext.getCurrentInstance().addCallbackParam("success", success); 
    }
    
    public void delete() {
        boolean success = savhelper.deleteData(savwd);
                
        this.editMode = !success;
        Messager.showDeleteStatus(success);     
    }
    
    public void trySave() {
        if (this.validate()) this.save();
    }

    public String getDefaultButton() {
        return defaultButton;
    }

    public void setDefaultButton(String defaultButton) {
        this.defaultButton = defaultButton;
    }

    public void handleCloseLookup(CloseEvent event) {
        this.showLookup=false;
    }
    
    private void ambilUser() {
        FacesContext context = FacesContext.getCurrentInstance();
        LoginBean logBean = (LoginBean) context.getApplication().evaluateExpressionGet(context, "#{loginBean}", LoginBean.class);
        this.user = logBean.getSelectedUser();
    }
    
}

